package com.sunda.spmswms.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sunda.spmswms.entity.CostCenter;
import com.sunda.spmswms.mapper.CostCenterMapper;
import com.sunda.spmswms.service.ICostCenterService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Map;

/**
 * <p>
 * 仓库信息表 服务实现类
 * </p>
 *
 * @author Wayne
 * @since 2020-11-24
 */
@Service
@Slf4j
public class CostCenterServiceImpl extends ServiceImpl<CostCenterMapper, CostCenter> implements ICostCenterService {

    @Autowired
    CostCenterMapper costCenterMapper;

    @Override
    public List<CostCenter> getCostCenterList() {
        return costCenterMapper.selectList(new QueryWrapper<>());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertCostCenter(JSONObject doc) {
        try {
            JSONArray array = doc.getJSONArray("Z_SPMS_GETCOSTCENTER_IT_CSKS");
            for(int i = 0; i<array.size(); i++) {
                System.out.println("=======" + array.size() + "    " + i + "   SAP 成本中心信息  " + array.get(i).toString());
                JSONArray json = JSONArray.parseArray(array.get(i).toString());
                if (i > 0){
                    CostCenter costCenter = new CostCenter();
                    costCenter.setCompanyCode(json.getString(0));
                    costCenter.setCostCenterCode(json.getString(1));
                    costCenter.setCostCenterName(json.getString(2));
                    if (costCenterMapper.selectOne(new QueryWrapper<CostCenter>().eq("costCenter", costCenter.getCostCenterCode())) != null){
                        costCenterMapper.update(costCenter, new QueryWrapper<CostCenter>().eq("costCenter", costCenter.getCostCenterCode()));
                    }else {
                        costCenterMapper.insert(costCenter);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            log.info("=========== CostCenterServiceImpl.insertCostCenter 执行异常 " + e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }

    @Override
    public List<Map<String, Object>> getCostCenterByWerks(String werks) {
        if (StringUtils.isEmpty(werks)){
            return null;
        }
        return this.baseMapper.getCostCenterByWerks(werks);
    }
}
